import { deleteRecord, pageRecord, searchTreeSource, updateRecordState } from '@/services/api/api-publicity-record';
import { ModalForm } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { Space, Tag, message } from 'antd';
import { DefaultOptionType } from 'antd/lib/select';
import 'dayjs/locale/zh-cn';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import AddRecord from './components/record/AddRecord';
import DetailsRecord from './components/record/DetailsRecord';
import DetailsSource from './components/source/DetailsSource';

export default (): React.ReactNode => {
  const access = useAccess();

  const actionRef = useRef<ActionType>();
  //来源列表
  const [sourceSelections, setSourceSelectionsState] = useState<any[]>([])
  /**
  * 加载 来源 列表
  * @param key
  */
  const treeOrganizationData = async () => {
    try {
      const response = await searchTreeSource();
      if (response.code === 0) {
        setSourceSelectionsState(response.data);
      }
    } catch (error) { }
  };
  const filter = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );
  const displayRender = (labels: string[], selectedOptions: DefaultOptionType[]) =>
    labels.map((label, i) => {
      const option = selectedOptions[i];
      if (i === labels.length - 1) {
        return (
          <span key={option.value}>
            {label}
          </span>
        );
      }
      return <span key={option.value}>{label} / </span>;
    });

  /**
   * 获取来源类型
   */
  useEffect(() => {
    treeOrganizationData();
  }, []);


  const columns: ProColumns<PublicityRecordData.Record>[] = [
    {
      title: '来源',
      dataIndex: 'sourceIds',
      hideInTable: true,
      // width: '250px',
      align: 'center',
      colSize: 4,
      valueType: 'cascader',
      fieldProps: {
        multiple: true,
        options: sourceSelections,
        showSearch: { filter },
        changeOnSelect: true,
        showCheckedStrategy: 'SHOW_CHILD',
        displayRender: displayRender,
        maxTagCount: 4
      },
      key: 'sourceIds',
    },
    {
      title: '状态',
      dataIndex: 'state',
      ellipsis: true,
      width: '50px',
      fixed: 'left',
      align: 'center',
      valueType: 'select',
      valueEnum: {
        1: { text: '开启' },
        0: { text: '关闭' },
      },
      hideInTable: access.宣传刊播x配置x预览者,
      render: (_, row) => {
        return (
          <Tag color={row.state === 1 ? 'green' : 'orange'}>
            {row.state === 1 ? '开启' : '关闭'}
          </Tag>
        );
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      ellipsis: true,
      width: '150px',
      fixed: 'left',
      align: 'center',
      render: (_, row) => {
        return (
          <div
            style={{
              textAlign: 'left',
              textOverflow: 'ellipsis',
              whiteSpace: "nowrap",
              overflow: 'hidden'
            }}
          >
            {/* {row.isFile === 1 ? <PaperClipOutlined /> : <></>} */}
            <DetailsRecord id={row.id} name={row.title} onRefurbish={() => { }} />
          </div>
        );
      },
    },
    {
      title: '发布日期',
      key: 'publishTimes',
      dataIndex: 'publishTime',
      valueType: 'dateRange',
      width: '70px',
      align: 'center',
      hideInSearch: true,
      fieldProps: {
        allowClear: true,
        placeholder: ['开始日期', '结束日期'],
        format: 'YYYY-MM-DD',
        ranges: {
          今日: [moment(), moment()],
          本月: [moment().startOf('month'), moment().endOf('month')],
          上月: [
            moment().startOf('month').subtract(1, 'months'),
            moment().endOf('month').subtract(1, 'months'),
          ],
          最近7天: [moment().subtract(6, 'days'), moment()],
          最近60天: [moment().subtract(59, 'days'), moment()],
          最近90天: [moment().subtract(89, 'days'), moment()],
        },
      },
      render: (_, row) => {
        return <span>{moment(row.publishTime).format('YYYY-MM-DD')}</span>;
      },
    },
    {
      title: '来源类型',
      dataIndex: 'sourceTopName',
      hideInSearch: true,
      align: 'center',
      width: '110px',
      
      render: (_, row) => {
        return <Tag color={row.sourceTopName == "中央媒体" ? "red" : row.sourceTopName == "市/区县级媒体" ? "green" : "blue"}>{row.sourceTopName}</Tag>;
      },
    },

    {
      title: '来源',
      dataIndex: 'sourceIds',
      hideInSearch: true,
      width: '250px',
      align: 'center',
      key: 'sourceIds',
      render: (_, row) => {
        return (
          <div
            style={{
              textAlign: 'left',
              overflow: 'hidden'
            }}
          >
            <Space>
              {row.sourceNames.map((item) => (
                <Tag key={item}  color={ Number(row.score) > 0 ? '' : Number(row.score) == 0 ? '#FFD591' : 'red' }>{item}</Tag>
              ))}
            </Space>
          </div>
        );
      },
    },
    {
      title: '积分',
      dataIndex: 'score',
      width: '30px',
      align: 'center',
      hideInSearch: true,
      hideInTable: access.宣传刊播x配置x预览者,
      render: (_, row) => {
        return (
          <div
            style={{ color: Number(row.score) > 0 ? '' : Number(row.score) == 0 ? '#FFD591' : 'red' }}
          >
            {row.score}
          </div>
        );
      },
    },
    {
      title: '创建时间',
      key: 'createdTimes',
      dataIndex: 'createdTime',
      valueType: 'dateRange',
      width: '100px',
      align: 'center',
      hideInSearch: true,
      fieldProps: {
        allowClear: true,
        placeholder: ['开始日期', '结束日期'],
        format: 'YYYY-MM-DD',
        ranges: {
          今日: [moment(), moment()],
          本月: [moment().startOf('month'), moment().endOf('month')],
          上月: [
            moment().startOf('month').subtract(1, 'months'),
            moment().endOf('month').subtract(1, 'months'),
          ],
          最近7天: [moment().subtract(6, 'days'), moment()],
          最近60天: [moment().subtract(59, 'days'), moment()],
          最近90天: [moment().subtract(89, 'days'), moment()],
        },
      },
      render: (_, row) => {
        return <span>{row.createdTime}</span>;
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: '50px',
      align: 'center',
      hideInTable: !(access.宣传刊播x配置x管理员 && access.宣传刊播x更新),
      render: (text, row, _, action) => [
        access.宣传刊播x配置x管理员 && access.宣传刊播x更新 && (
          <a
            key="update_state"
            onClick={async () => {
              const response = await updateRecordState({ id: row.id });
              if (response.code === 0) {
                message.success('更新成功！');
                action?.reload();
              }
            }}
          >
            {row.state === 1 ? '关闭' : '开启'}
          </a>
        ),
        access.宣传刊播x配置x管理员 && access.宣传刊播x更新 && (<ModalForm
          key={"delete_record_modal_form"}
          title="是否删除"
          trigger={
            <a key="delete_record_a">删除</a>
          }
          autoFocusFirstInput
          modalProps={{
            width: 400,
            destroyOnClose: true,
          }}
          onFinish={async (values) => {
            const response = await deleteRecord({ id: row.id });
            if (response.code === 0) {
              message.success('删除成功！');
              action?.reload()
              return true;
            }
          }}
        >
          该记录将会被删除，是否确定
        </ModalForm>),
      ],
    },
  ];

  /**
   * 请求网络
   * @param value
   */
  const request = async (params = {}) => {
    if (params.sourceIds) {
      const sourceIds = params.sourceIds.map(item => item.join(","))
      params.sourceIds = sourceIds
    }
    const response = await pageRecord({ ...params });
    return Promise.resolve({
      data: response.data.data,
      total: response.data.total,
      success: response.code === 0,
    });
  };

  return (
    <PageContainer
      breadcrumb={{}}
      extra={[
        access.宣传刊播x配置x管理员 && access.宣传刊播x来源 && (
          <DetailsSource
            onRefurbish={() => {
              actionRef.current?.reload();
            }}
          />
        ),
        access.宣传刊播x配置x管理员 && access.宣传刊播x创建 && (
          <AddRecord
            onRefurbish={() => {
              actionRef.current?.reload();
            }}
          />
        ),
      ]}
    >
      <ProTable<PublicityRecordData.Record>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        rowKey="id"
        tableLayout="fixed"
        dateFormatter="string"
        search={{
          collapsed: false,
          labelWidth: 'auto',
          collapseRender: false,
        }}
        request={request}
        sticky
        scroll={{
          x: '1300px',
        }}
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          defaultPageSize: 20,
        }}
        // search={false}
        toolBarRender={() => []}
      />
    </PageContainer>
  );
};
